package com.ittao.taopicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ittao.taopicturebackend.api.aliyun.AliYunAiApi;
import com.ittao.taopicturebackend.api.aliyun.model.CreateOutPaintingTaskRequest;
import com.ittao.taopicturebackend.api.aliyun.model.CreateOutPaintingTaskResponse;
import com.ittao.taopicturebackend.config.CosClientConfig;
import com.ittao.taopicturebackend.exception.BusinessException;
import com.ittao.taopicturebackend.exception.ErrorCode;
import com.ittao.taopicturebackend.exception.ThrowUtils;
import com.ittao.taopicturebackend.manager.cos.CosManager;
import com.ittao.taopicturebackend.manager.upload.UrlPictureUpload;
import com.ittao.taopicturebackend.manager.upload.PictureUploadTemplate;
import com.ittao.taopicturebackend.manager.upload.FilePictureUpload;
import com.ittao.taopicturebackend.model.dto.file.UploadPictureResult;
import com.ittao.taopicturebackend.model.dto.picture.*;
import com.ittao.taopicturebackend.model.entity.Picture;
import com.ittao.taopicturebackend.model.entity.Space;
import com.ittao.taopicturebackend.model.entity.User;
import com.ittao.taopicturebackend.model.enums.PictureCategoryEnum;
import com.ittao.taopicturebackend.model.enums.PictureReviewStatusEnum;
import com.ittao.taopicturebackend.model.enums.PictureTagEnum;
import com.ittao.taopicturebackend.model.vo.PictureVO;
import com.ittao.taopicturebackend.model.vo.UserVO;
import com.ittao.taopicturebackend.service.PictureService;
import com.ittao.taopicturebackend.mapper.PictureMapper;
import com.ittao.taopicturebackend.service.SpaceService;
import com.ittao.taopicturebackend.service.UserService;
import com.ittao.taopicturebackend.utils.BingImageCrawlerUtils;
import com.ittao.taopicturebackend.utils.ColorSimilarUtils;
import com.ittao.taopicturebackend.utils.ColorTransformUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.time.Duration;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 86134
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-07-21 15:04:48
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    // @Resource
    // private FileManager fileManager;

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private AliYunAiApi aliYunAiApi;

    /**
     * Caffeine 缓存，用于存储图数据
     */
    private final Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder()
            .initialCapacity(1024) // 初始容量
            .maximumSize(10_000L) // 最大容量
            .expireAfterWrite(Duration.ofMinutes(5)) // 写入后 5 分钟过期
            .build();

    /**
     * 校验图片对象
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }


    /**
     * 上传图片
     *
     * @param inputSource          文件输入源
     * @param pictureUploadRequest 上传请求参数
     * @param loginUser            当前登录用户
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 校验是否有空间的权限，仅空间管理员才能上传（改为使用sa-token统一的权限校验）
            // if (!loginUser.getId().equals(space.getUserId())) {
            //     throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            // }
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }

        }

        // 判断是新增还是删除
        Long pictureId;
        pictureId = pictureUploadRequest.getId();
        // 如果是更新，判断图片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // // 仅本人或管理员可更新（改为使用sa-token统一的权限校验）
            // if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            //     throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            // }
            // 校验空间是否一致
            // 没传 spaceId，则复用原有图片的 spaceId （这样也兼容了公共图库）
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                } else {
                    if (ObjUtil.notEqual(spaceId, null)) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间不一致，不能更新");
                    }
                }
            }
        }
        // 上传图片，得到图片信息
        // 根据用户 id 划分目录 => 按照空间划分目录
        String uploadPathPrefix;
        if (spaceId == null) {
            // 公共图库
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            // 私有空间
            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        // 根据 inputSource 的类型判断上传方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        // 构造要入库的图片信息
        Picture picture = new Picture();
        picture.setSpaceId(spaceId); // 指定空间 id
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setOriginalUrl(uploadPictureResult.getOriginalUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        String picName = uploadPictureResult.getPicName();
        // 支持外层传递图片名称
        if (StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setPicColor(ColorTransformUtils.getStandarColor(uploadPictureResult.getPicColor()));
        picture.setUserId(loginUser.getId());

        // 设置分类和标签（如果有传递）
        if (StrUtil.isNotBlank(pictureUploadRequest.getPicCategory())) {
            picture.setCategory(pictureUploadRequest.getPicCategory());
        }
        if (StrUtil.isNotBlank(pictureUploadRequest.getPicTags())) {
            picture.setTags(pictureUploadRequest.getPicTags());
        }

        // 填充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库
        // 如果 pictureId 不为空，说明是更新操作，否则是新增操作
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }

        // 开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            // 插入数据
            boolean result = this.saveOrUpdate(picture);
            // 如果是更新操作，清理旧图片文件
            if (finalSpaceId != null && result) {
                // 清理旧图片文件
                Picture oldPicture = this.getById(finalSpaceId);
                if (oldPicture != null) {
                    this.clearPictureFile(oldPicture);
                }
            }
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败，数据库操作失败");
            // 更新空间的总大小和总数量，公共图库不需要更新空间信息
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });
        return PictureVO.objToVo(picture);
    }

    /**
     * 对象转封装类
     *
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 获取图片包装类（单条 ）
     *
     * @param picturePage
     * @param request
     * @return
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream()
                .map(Picture::getUserId)
                .collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }


    /**
     * 获取查询对象
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }

        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();

        // 修复后的正确逻辑
        if (nullSpaceId) {
            // 公共图库查询：只查询 spaceId 为 null 的图片
            queryWrapper.isNull("spaceId");
        } else if (ObjUtil.isNotEmpty(spaceId)) {
            // 个人空间查询：只查询指定 spaceId 的图片
            queryWrapper.eq("spaceId", spaceId);
        }
        // 注意：如果既不是 nullSpaceId 也没有指定 spaceId，则不添加 spaceId 相关条件（管理员查询所有）

        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            // and (name like "%xxx%" or introduction like "%xxxx%")
            queryWrapper.and(qw -> qw
                    .like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        // >= startEditTime
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        // < endEditTime
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);

        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                // and (tag like like "%\"Java\"%" and like "%\"Python\"%")
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);

        // 增强时间排序支持
        if (StrUtil.isBlank(sortField)) {
            // 默认按创建时间降序排列（最新的图片在前）
            queryWrapper.orderByDesc("createTime");
        } else if ("createTime".equals(sortField) || "updateTime".equals(sortField) || "editTime".equals(sortField)) {
            // 时间字段特殊处理，确保索引生效
            if ("ascend".equals(sortOrder)) {
                queryWrapper.orderByAsc(sortField);
            } else {
                queryWrapper.orderByDesc(sortField);
            }
            log.info("应用时间排序: {} {}", sortField, sortOrder);
        }
        return queryWrapper;
    }

    /**
     * 图片审核
     *
     * @param pictureReviewRequest
     * @param loginUser
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);

        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (id == null || reviewStatus == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2. 判断图片是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        // 3. 校验审核状态是否重复
        if (oldPicture.getReviewStatus().equals(reviewStatus)) {
            // 如果图片已经审核过了，不能重复审核
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片已审核，不能重复审核");
        }
        // 4. 数据库操作
        Picture updatePicture = new Picture();
        BeanUtil.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean result = this.updateById(updatePicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * 填充审核参数
     *
     * @param picture   图片对象
     * @param loginUser 当前登录用户
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        // 管理员自动过审
        if (userService.isAdmin(loginUser)) {
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动审核通过");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，无论是编辑还是创建默认都是待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    /**
     * 网页抓取图片
     *
     * @param pictureUploadByBatchRequest 抓取请求
     * @param loginUser                   发出抓取的用户
     * @return 抓取成功图片数量
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 校验参数
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        String category = pictureUploadByBatchRequest.getCategory();
        List<String> tags = pictureUploadByBatchRequest.getTags();

        // 验证分类是否在预定义范围内
        if (StrUtil.isNotBlank(category)) {
            PictureCategoryEnum categoryEnum = PictureCategoryEnum.getEnumByValue(category);
            ThrowUtils.throwIf(categoryEnum == null, ErrorCode.PARAMS_ERROR, "分类不在预定义范围内");
        }

        // 验证标签是否在预定义范围内
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                PictureTagEnum tagEnum = PictureTagEnum.getEnumByValue(tag);
                ThrowUtils.throwIf(tagEnum == null, ErrorCode.PARAMS_ERROR, "标签 " + tag + " 不在预定义范围内");
            }
        }

        // 名称前缀默认为搜索关键词
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        }

        ThrowUtils.throwIf(count > 50, ErrorCode.PARAMS_ERROR, "批量抓取图片数量不能超过 50");

        // 使用优化的工具类获取已存在的图片URL集合
        Set<String> existingUrls = BingImageCrawlerUtils.getExistingPictureUrls(this, loginUser, null);

        log.info("开始优化批量抓取 - 关键词: {}, 目标: {}张", searchText, count);

        // 使用优化的多样化抓取方法
        List<String> diverseImageUrls = BingImageCrawlerUtils.crawlDiverseImages(searchText, count, existingUrls);

        int uploadCount = 0;
        for (String fileUrl : diverseImageUrls) {
            if (uploadCount >= count) {
                break;
            }

            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileUrl(fileUrl);
            pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));

            // 批量设置分类和标签
            if (StrUtil.isNotBlank(category)) {
                pictureUploadRequest.setPicCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                pictureUploadRequest.setPicTags(JSON.toJSONString(tags));
            }

            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);

                // 记录原始图片URL到数据库
                Picture updatePicture = new Picture();
                updatePicture.setId(pictureVO.getId());
                updatePicture.setOriginalUrl(fileUrl);
                this.updateById(updatePicture);

                uploadCount++;
                log.info("优化抓取上传成功: {} ({}/{})", pictureVO.getId(), uploadCount, count);

            } catch (Exception e) {
                log.warn("优化抓取上传失败: {}, 错误: {}", fileUrl, e.getMessage());
                // 继续处理下一张图片
            }
        }

        log.info("优化批量抓取完成 - 目标: {}张, 实际成功: {}张, 多样性提升: {}%",
                count, uploadCount, (uploadCount * 100 / Math.max(diverseImageUrls.size(), 1)));
        return uploadCount;
    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (StrUtil.isBlank(nameRule) || CollUtil.isEmpty(pictureList)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("批量解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }

    /**
     * 分页查询图片列表，缓存优化
     *
     * @param pictureQueryRequest 查询条件
     * @param current             当前页码
     * @param size                每页大小
     * @param request             HTTP 请求对象
     * @return 分页结果
     */
    @Override
    public Page<PictureVO> listPictureVOByPageWithCache(PictureQueryRequest pictureQueryRequest, long current, long size, HttpServletRequest request) {
        // 查询缓存，缓存没有则查询数据库
        // 构建缓存的 key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String cacheKey = String.format("taopicture:listPictureVOByPage:%s", hashKey);

        // 1. 先从本地缓存中查询
        String cachedValue = LOCAL_CACHE.getIfPresent(cacheKey);
        if (cachedValue != null) {
            // 本地缓存命中，直接返回
            return JSONUtil.toBean(cachedValue, Page.class);
        }

        // 2. 如果本地缓存没有，则查询 Redis 分布式缓存
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        cachedValue = opsForValue.get(cacheKey);
        if (cachedValue != null) {
            // Redis 缓存命中，更新本地缓存，返回结果
            LOCAL_CACHE.put(cacheKey, cachedValue);
            return JSONUtil.toBean(cachedValue, Page.class);
        }

        // 3. 查询数据库
        Page<Picture> picturePage = this.page(new Page<>(current, size),
                this.getQueryWrapper(pictureQueryRequest));

        // 4. 更新缓存
        Page<PictureVO> pictureVOPage = this.getPictureVOPage(picturePage, request);
        // 将结果转换为 JSON 字符串存入缓存
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        // 设置缓存的过期时间，5 - 10 分钟过期（防止缓存雪崩）
        int cacheExpireTime = 5 * 60 + RandomUtil.randomInt(0, 5 * 60); // 5 分钟到 10 分钟之间
        opsForValue.set(cacheKey, cacheValue, cacheExpireTime, TimeUnit.SECONDS);
        // 4.2 同时更新本地缓存
        LOCAL_CACHE.put(cacheKey, cacheValue);
        // 5. 返回结果
        return pictureVOPage;
    }

    /**
     * 清除图片文件
     *
     * @param oldPicture 旧图片对象
     */
    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }

        // 从完整URL提取对象键
        String compressedKey = null;
        if (StrUtil.isNotBlank(pictureUrl)) {
            if (!pictureUrl.startsWith("http")) {
                compressedKey = pictureUrl;
            } else {
                String domain = cosClientConfig.getHost();
                if (StrUtil.isNotBlank(domain)) {
                    if (domain.startsWith("http://")) {
                        domain = domain.substring(7);
                    } else if (domain.startsWith("https://")) {
                        domain = domain.substring(8);
                    }
                    if (!domain.endsWith("/")) {
                        domain = domain + "/";
                    }
                    String domainPrefix = "https://" + domain;
                    if (pictureUrl.startsWith(domainPrefix)) {
                        compressedKey = pictureUrl.substring(domainPrefix.length());
                    } else {
                        domainPrefix = "http://" + domain;
                        if (pictureUrl.startsWith(domainPrefix)) {
                            compressedKey = pictureUrl.substring(domainPrefix.length());
                        }
                    }
                }
            }
        }

        if (StrUtil.isBlank(compressedKey)) {
            log.warn("无法提取压缩图对象键: {}", pictureUrl);
            return;
        }

        // 1. 删除压缩图文件（webp格式）
        try {
            cosManager.deleteObject(compressedKey);
            log.info("删除压缩图: {}", compressedKey);
        } catch (Exception e) {
            log.warn("删除压缩图失败: {}", compressedKey, e);
        }

        // 2. 删除缩略图文件
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            String thumbnailKey = null;
            if (!thumbnailUrl.startsWith("http")) {
                thumbnailKey = thumbnailUrl;
            } else {
                String domain = cosClientConfig.getHost();
                if (StrUtil.isNotBlank(domain)) {
                    if (domain.startsWith("http://")) {
                        domain = domain.substring(7);
                    } else if (domain.startsWith("https://")) {
                        domain = domain.substring(8);
                    }
                    if (!domain.endsWith("/")) {
                        domain = domain + "/";
                    }
                    String domainPrefix = "https://" + domain;
                    if (thumbnailUrl.startsWith(domainPrefix)) {
                        thumbnailKey = thumbnailUrl.substring(domainPrefix.length());
                    } else {
                        domainPrefix = "http://" + domain;
                        if (thumbnailUrl.startsWith(domainPrefix)) {
                            thumbnailKey = thumbnailUrl.substring(domainPrefix.length());
                        }
                    }
                }
            }

            if (StrUtil.isNotBlank(thumbnailKey)) {
                try {
                    cosManager.deleteObject(thumbnailKey);
                    log.info("删除缩略图: {}", thumbnailKey);
                } catch (Exception e) {
                    log.warn("删除缩略图失败: {}", thumbnailKey, e);
                }
            }
        }

        // 3. 删除原图文件 - 压缩图去掉.webp，加上原格式
        if (compressedKey.endsWith(".webp")) {
            String basePath = compressedKey.substring(0, compressedKey.lastIndexOf(".webp"));
            String[] extensions = {"jpg", "jpeg", "png", "gif", "bmp"};
            for (String ext : extensions) {
                String originalKey = basePath + "." + ext;
                try {
                    cosManager.deleteObject(originalKey);
                    log.info("删除原图: {}", originalKey);
                    break; // 删除成功就退出
                } catch (Exception e) {
                    // 文件不存在，继续尝试下一个格式
                }
            }
        }
    }

    /**
     * 检查图片权限
     *
     * @param loginUser
     * @param picture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        Long loginUserId = loginUser.getId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUserId) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅本人可操作
            if (!picture.getUserId().equals(loginUserId)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    /**
     * 删除图片
     *
     * @param pictureId
     * @param loginUser
     */
    @Override
    public void deletePicture(long pictureId, User loginUser) {
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 校验图片是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限,// 权限校验，已经修改为注解鉴权
        // this.checkPictureAuth(loginUser, oldPicture);

        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除图片失败");
            if (oldPicture.getSpaceId() != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, oldPicture.getSpaceId())
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 清理图片资源
        this.clearPictureFile(oldPicture);
    }

    /**
     * 编辑图片
     *
     * @param pictureEditRequest
     * @param loginUser
     */
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        // 填充审核参数
        this.fillReviewParams(picture, loginUser);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 权限校验，已经修改为注解鉴权
        // this.checkPictureAuth(loginUser, oldPicture);
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * 根据颜色搜索图片
     *
     * @param spaceId   空间ID
     * @param picColor  图片颜色
     * @param loginUser 当前登录用户
     * @return 符合条件的图片列表
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 3. 查询该空间下的所有图片（必须要有主色调）
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor) // 确保有主色调
                .list();
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return new ArrayList<>();
        }
        // 将颜色字符串转为主色调
        Color targetColor = Color.decode(picColor);
        // 4. 计算相似度并排序，只保留相似度高于80%的图片
        List<Picture> sortedPictureList = pictureList.stream()
                .filter(picture -> {
                    String hexColor = picture.getPicColor();
                    if (StrUtil.isBlank(hexColor)) {
                        return false;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 计算相似度，只保留相似度大于0.8的图片
                    double similarity = ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                    return similarity > 0.8;
                })
                .sorted(Comparator.comparingDouble(picture -> {
                    String hexColor = picture.getPicColor();
                    Color pictureColor = Color.decode(hexColor);
                    // 计算相似度，越大越相似
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                .limit(10)// 取前 10 个
                .collect(Collectors.toList());
        // 5. 返回结果
        return sortedPictureList.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    /**
     * 批量编辑图片
     *
     * @param pictureEditByBatchRequest
     * @param loginUser
     */
    @SuppressWarnings("SpringTransactionalMethodCallsInspection")
    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        // 1. 获取和校验参数
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        // 3. 查询指定图片（仅选择需要的字段）
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if (pictureList.isEmpty()) {
            return;
        }
        // 4. 更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);

        // 5. 操作数据库进行批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "批量编辑图片失败");
    }

    /**
     * AI 扩图任务
     *
     * @param createPictureOutPaintingTaskRequest
     * @param loginUser
     * @return
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验，已经修改为注解鉴权
        // checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

}
